﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace TripLOAMobile
{
    class FormBuffer
    {
        private Stack<Form> buffer;
        private Stack<string> names;
        private Welcome baseForm;
        private bool goTo;
    
        public FormBuffer(Welcome baseForm)
        {
            this.baseForm = baseForm;
            buffer = new Stack<Form>(5);
            names = new Stack<string>(5);
            goTo = false;
        }

        public void Close()
        {
            Form temp = buffer.Pop();
            names.Pop();
            if (goTo)
            {
                temp.Dispose();
                if (buffer.Count == 0)
                {
                    baseForm.Activate();
                    goTo = false;
                }
                else buffer.Peek().Activate();
            }
            else
            {
                temp.Close();
            }
        }

        public void Add(Form f, string name)
        {
            buffer.Push(f);
            names.Push(name);
        }

        public string[] GetFormNames()
        {
            return names.ToArray();
        }

        public void GoTo(string name)
        {
            Form temp;
            while (!name.Equals(names.Peek()))
            {
                temp = buffer.Pop();
                temp.Dispose();
                names.Pop();                
            }
            temp = buffer.Peek();
            temp.Activate();
            goTo = true;
        }

        public void Clear()
        {
            bool invoke = false;
            Form f;
            while (buffer.Count > 0)
            {
                f = buffer.Pop();
                if (f is InsertTravel)
                {
                    ((InsertTravel)f).Invoke(((InsertTravel)f).DelegateDispose);
                    invoke = true;
                }
                else
                {
                    if (f is SearchTravel)
                    {
                        ((SearchTravel)f).Invoke(((SearchTravel)f).DelegateDispose);
                        invoke = true;
                    }
                    else f.Dispose();
                }
 
            }
            if (invoke) baseForm.Invoke(baseForm.DelegateActivate);
            else baseForm.Activate();
            names.Clear();
            if (goTo) goTo = false;
        }
    }
}
